<template>
  <div>
    <editor
      v-model="contentValue"
      :init="init"
      :disabled="disabled"
      v-if="visible"
      @onClick="onClick"
    ></editor>
  </div>
</template>
<script>
import tinymce from "tinymce/tinymce"; // tinymce默认hidden，不引入则不显示编辑器
import Editor from "@tinymce/tinymce-vue"; // 引入tinymce编辑器
import "tinymce/themes/silver"; // 编辑器主题，不引入则报错
// import '/public/tinymce/icons/default/icons.min.js'
import "tinymce/icons/default/icons"; // 引入编辑器图标icon，不引入则不显示对应图标

// 引入编辑器插件（基本免费插件都在这儿了）
import "tinymce/plugins/advlist"; // 高级列表
import "tinymce/plugins/anchor"; // 锚点
import "tinymce/plugins/autolink"; // 自动链接
import "tinymce/plugins/autoresize"; // 编辑器高度自适应,注：plugins里引入此插件时，Init里设置的height将失效
import "tinymce/plugins/autosave"; // 自动存稿
import "tinymce/plugins/charmap"; // 特殊字符
import "tinymce/plugins/code"; // 编辑源码
import "tinymce/plugins/codesample"; // 代码示例
import "tinymce/plugins/directionality"; // 文字方向
import "tinymce/plugins/emoticons"; // 表情
import "tinymce/plugins/fullpage"; // 文档属性
import "tinymce/plugins/fullscreen"; // 全屏
import "tinymce/plugins/help"; // 帮助
import "tinymce/plugins/hr"; // 水平分割线
import "tinymce/plugins/image"; // 插入编辑图片
// import 'tinymce/plugins/imagetools' // 插入编辑图片
import "tinymce/plugins/importcss"; // 引入css
import "tinymce/plugins/insertdatetime"; // 插入日期时间
import "tinymce/plugins/link"; // 超链接
import "tinymce/plugins/lists"; // 列表插件
import "tinymce/plugins/media"; // 插入编辑媒体
import "tinymce/plugins/nonbreaking"; // 插入不间断空格
import "tinymce/plugins/pagebreak"; // 插入分页符
import "tinymce/plugins/paste"; // 粘贴插件
import "tinymce/plugins/preview"; // 预览
import "tinymce/plugins/print"; // 打印
import "tinymce/plugins/quickbars"; // 快速工具栏
import "tinymce/plugins/save"; // 保存
import "tinymce/plugins/searchreplace"; // 查找替换
// import 'tinymce/plugins/spellchecker'  //拼写检查，暂未加入汉化，不建议使用
import "tinymce/plugins/tabfocus"; // 切入切出，按tab键切出编辑器，切入页面其他输入框中
import "tinymce/plugins/table"; // 表格
import "tinymce/plugins/template"; // 内容模板
import "tinymce/plugins/textcolor"; // 文字颜色
import "tinymce/plugins/textpattern"; // 快速排版
import "tinymce/plugins/toc"; // 目录生成器
import "tinymce/plugins/visualblocks"; // 显示元素范围
import "tinymce/plugins/visualchars"; // 显示不可见字符
import "tinymce/plugins/wordcount"; // 字数统计

// 扩展插件
// import 'tinymce/plugins/ax_wordlimit'// 字数限制插件
// import 'tinymce/plugins/axupimgs'// ax多图片批量上传
import "tinymce/plugins/bdmap"; // 百度地图
import "tinymce/plugins/indent2em"; // 首行缩进
//import "tinymce/plugins/kityformula-editor"; // 数学公式
// import 'tinymce/plugins/powerpaste'//word 导入
// import 'tinymce/plugins/responsivefilemanager'

export default {
  name: "TinymceEditor",
  components: {
    Editor,
  },
  props: {
    value: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    plugins: {
      type: [String, Array],
      default:
        "print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists textpattern emoticons autosave bdmap indent2em",
    },
    toolbar: {
      type: [String, Array],
      default:
        "code undo redo restoredraft | forecolor backcolor bold italic underline strikethrough | alignleft aligncenter alignright alignjustify outdent indent indent2em lineheight | print preview fullscreen | styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | table charmap emoticons hr pagebreak insertdatetime | image media link anchor bdmap",
    },
    fontsizeFormats: {
      type: [String, Array],
      default: "6px 8px 10px 12px 14px 16px 18px 24px 36px",
    },
    fontFormats: {
      type: [String, Array],
      default:
        "微软雅黑='微软雅黑'; 宋体='宋体'; 黑体='黑体'; 仿宋='仿宋'; 楷体='楷体'; 隶书='隶书'; 幼圆='幼圆'; 方正舒体='方正舒体'; 方正姚体='方正姚体'; 等线='等线'; 华文彩云='华文彩云'; 华文仿宋='华文仿宋'; 华文行楷='华文行楷'; 华文楷体='华文楷体'; 华文隶书='华文隶书'; Andale Mono=andale mono,times; Arial=arial; Arial Black=arial black;avant garde; Book Antiqua=book antiqua;palatino; Comic Sans MS=comic sans ms; Courier New=courier new;courier; Georgia=georgia; Helvetica=helvetica; Impact=impact;chicago; Symbol=symbol; Tahoma=tahoma;arial; sans-serif; Terminal=terminal,monaco; Times New Roman=times new roman,times; Trebuchet MS=trebuchet ms; Verdana=verdana;geneva; Webdings=webdings; Wingdings=wingdings",
    },
    filePickerUrl: {
      type: String,
      default: `${process.env.VUE_APP_API_BASE_URL}/fmsel.html`,
    },
    imagesUploadUrl: {
      type: String,
      default: `${process.env.VUE_APP_API_BASE_URL}/elfinder/connector?cmd=upload&target=A_SW1hZ2U_E`,
    },
  },
  data() {
    return {
      // 解决 tinymce 不能获取焦点的问题
      visible: false,
      init: {
        base_url: "/tinymce", // 设置主程序结构所在url
        // auto_focus: true,
        // suffix: '.min',
        theme: "silver", // 主题
        zIndex: 2200,
        placeholder: "请输入...",
        language_url: "/tinymce/langs/zh_CN.js", // 如果语言包不存在，指定一个语言包路径
        language: "zh_CN", // 语言
        skin_url: "/tinymce/skins/ui/oxide", // 皮肤：浅色
        // skin_url: '/tinymce/skins/ui/oxide-dark',//皮肤：暗色
        // content_css: '/static/plugins/tinymce/mycontent.css',// 内容的样式
        emoticons_database_url: "/tinymce/plugins/emoticons/js/emojis.js",
        height: 360,
        // width: this.calcWidth(),
        plugins: this.plugins, // 插件
        toolbar: this.toolbar, // 工具栏
        fontsize_formats: this.fontsizeFormats,
        font_formats: this.fontFormats,
        menubar: true, // 菜单栏
        branding: false, // 技术支持(Powered by Tiny || 由Tiny驱动)
        statusbar: true, // 显示底部状态栏 默认true
        readonly: false, // 设置只读属性 默认 false
        resize: true, // 调节编辑器大小 默认 true
        toolbar_sticky: true, // 粘性工具栏（或停靠工具栏）在向下滚动网页时将工具栏和菜单停靠在屏幕顶部，直到编辑器不再可见。
        // autosave_ask_before_unload: false,// 是否提示用户在尝试关闭当前窗口时提示他们有未保存的更改
        image_advtab: true, // 开启图片上传的高级选项功能
        // imagetools_cors_hosts: [ 'localhost:81', 'localhost:44326' ], // 设置跨域
        // imagetools_credentials_hosts: [ '200.0.0.220:81', 'localhost:44326' ],
        // imagetools_proxy: 'http://localhost:81',
        // imagetools_proxy: 'http://localhost:44326',
        // document_base_url：false,
        // remove_script_host: false,
        // powerpaste_word_import: 'propmt', // 参数可以是propmt, merge, clear，效果自行切换对比
        // powerpaste_html_import: 'propmt', // propmt, merge, clear
        // powerpaste_allow_local_images: true,
        // paste_data_images: true, // 图片是否可粘贴
        file_picker_types: "file image media",
        file_picker_callback: this.tinyBrowser,
        images_upload_handler: this.uploadHandler,
      },
      contentValue: this.value,
    };
  },
  watch: {
    value(newValue) {
      this.contentValue = newValue;
    },
    contentValue(newValue) {
      this.$emit("input", newValue);
    },
  },
  created() {},
  mounted() {
    this.$nextTick(function () {
      tinymce.init({});
      // 解决 tinymce 不能获取焦点的问题
      this.visible = true;
    });
  },
  methods: {
    // 添加相关的事件，可用的事件参照文档=> https://github.com/tinymce/tinymce-vue => All available events
    onClick(e) {
      this.$emit("onClick", e, tinymce);
    },
    // 清空内容
    clear() {
      this.contentValue = "";
    },
    calcWidth() {
      return document.body.clientWidth / 2 + "px";
    },
    tinyBrowser(callback, value, meta) {
      var tinymceWindow = tinymce.activeEditor.windowManager.openUrl({
        url:
          this.filePickerUrl +
          (meta.filetype == "image" || meta.filetype == "media"
            ? `?mimeType=${meta.filetype}`
            : ""), // 判断是否有文件类型，以便文件管理页面据此筛选
        title: "文件管理器",
      });
      window.addEventListener(
        "message",
        function (event) {
          // 返回结果就关闭弹窗
          var data = event.data;
          var url = process.env.VUE_APP_API_BASE_URL + data.url;
          var info = data.info;
          if (meta.filetype === "file") {
            callback(url, { text: info, title: info });
          }
          if (meta.filetype === "image") {
            callback(url, { alt: info });
          }
          if (meta.filetype === "media") {
            callback(url);
          }
          tinymceWindow.close();
        },
        false
      );
    },
    uploadHandler(blobInfo, succFun, failFun) {
      var xhr, formData;
      var file = blobInfo.blob(); // 转化为易于理解的file对象
      if (file.name === undefined && blobInfo.filename() !== undefined) {
        file.name = blobInfo.filename();
      }
      xhr = new XMLHttpRequest();
      xhr.withCredentials = false;
      xhr.open("POST", this.imagesUploadUrl);
      xhr.onload = function () {
        var json;
        if (xhr.status !== 200) {
          failFun("服务出现错误: " + xhr.status);
          return;
        }
        json = JSON.parse(xhr.responseText);
        if (
          !json ||
          !json.added ||
          json.added.length == 0 ||
          !json.added[0].hash
        ) {
          failFun("无效的 JSON: " + xhr.responseText);
          return;
        }
        var targetHash = json.added[0].hash;
        var imagePath = "/elfinder/connector?cmd=file&target=" + targetHash;
        succFun(process.env.VUE_APP_API_BASE_URL + imagePath);
      };
      formData = new FormData();

      // 这里的 upload[] 请与后台保持一致
      formData.append("upload[]", file, file.name);
      xhr.send(formData);
    },
  },
};
</script>
<style>
.tox-tinymce-aux {
  z-index: 200000;
}
</style>
